<?php

require_once __DIR__ . '/backend/support/bootstrap.php';

use app\model\BizModel;

echo "=== 服务项数据调试 ===\n";

// 1. 检查数据库字段
echo "1. 检查数据库字段:\n";
$columns = \support\Db::select("SHOW COLUMNS FROM " . get_table_prefix() . "biz");
foreach ($columns as $column) {
    if ($column->Field === 'service') {
        echo "  - service字段存在，类型: {$column->Type}\n";
        break;
    }
}

// 2. 查找有service数据的商家
echo "\n2. 查找有service数据的商家:\n";
$bizWithService = BizModel::whereNotNull('service')->where('service', '!=', '')->first();
if ($bizWithService) {
    echo "  - 找到商家: {$bizWithService->name}\n";
    echo "  - service原始值: '{$bizWithService->service}'\n";
    echo "  - service数组: " . implode(', ', $bizWithService->doServices()) . "\n";
} else {
    echo "  - 没有找到有service数据的商家\n";
    
    // 创建一个测试商家
    echo "  - 创建测试商家...\n";
    $testBiz = new BizModel();
    $testBiz->name = '测试商家';
    $testBiz->image = '/test/image.jpg';
    $testBiz->sort_by = 100;
    $testBiz->shop_address = '测试地址';
    $testBiz->biz_phone = '13800138000';
    $testBiz->uscc = '91110000123456789X';
    $testBiz->service = '餐饮服务@外卖配送@堂食服务';
    $testBiz->created_at = time();
    $testBiz->updated_at = time();
    
    if ($testBiz->save()) {
        echo "  - 测试商家创建成功，ID: {$testBiz->id}\n";
        echo "  - service值: '{$testBiz->service}'\n";
        $bizWithService = $testBiz;
    } else {
        echo "  - 测试商家创建失败\n";
    }
}

// 3. 模拟API查询
echo "\n3. 模拟API查询:\n";
if ($bizWithService) {
    $query = BizModel::query()
        ->select('*')
        ->where('id', $bizWithService->id)
        ->orderBy('sort_by', 'desc')
        ->orderBy('id', 'desc');
    
    $list = $query->get();
    
    foreach ($list as $item) {
        echo "  - 商家ID: {$item->id}\n";
        echo "  - 商家名称: {$item->name}\n";
        echo "  - service字段: '{$item->service}'\n";
        echo "  - service类型: " . gettype($item->service) . "\n";
        echo "  - service是否为空: " . (empty($item->service) ? '是' : '否') . "\n";
        
        // 模拟前端处理
        $serviceArray = $item->service && trim($item->service) ? explode('@', $item->service) : [];
        echo "  - 前端处理后的数组: " . implode(', ', $serviceArray) . "\n";
    }
}

// 4. 检查JSON序列化
echo "\n4. 检查JSON序列化:\n";
if ($bizWithService) {
    $jsonData = $bizWithService->toArray();
    echo "  - JSON数据中的service: " . ($jsonData['service'] ?? 'null') . "\n";
    
    // 模拟API响应
    $apiResponse = [
        'data' => [
            'list' => [$jsonData],
            'total' => 1
        ],
        'msg' => '获取成功',
        'code' => 20000
    ];
    
    echo "  - API响应中的service: " . ($apiResponse['data']['list'][0]['service'] ?? 'null') . "\n";
}

echo "\n=== 调试完成 ===\n"; 